package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a09_分割回文串复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/2/18
 */
public class a09_分割回文串复习2 {

    public static void main(String[] args) {
        a09_分割回文串复习2 test = new a09_分割回文串复习2();
        List<List<String>> aab = test.partition("aab");
        System.out.println(aab);
    }

    //aab
    public List<List<String>> partition(String s) {
        char[] chars = s.toCharArray();
        List<List<String>> result = new ArrayList<>();
        LinkedList<String> path = new LinkedList<>();
        traversal(result, path, chars, 0);
        return result;
    }

    private void traversal(List<List<String>> result,
                           LinkedList<String> path,
                           char[] chars,
                           int startIdx){
        if(startIdx == chars.length){
            result.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIdx; i < chars.length; i++) {
            if (isValid(chars, startIdx, i)) {
                path.add(splitArray(chars, startIdx, i));
                traversal(result, path, chars, i+1);
                path.removeLast();
            }else {
                continue;
            }
        }
    }

    private boolean isValid(char[] chars,int leftIdx,int rightIdx){
        while (leftIdx < rightIdx){
            if(chars[leftIdx] != chars[rightIdx]){
                return false;
            }
            leftIdx++;
            rightIdx--;
        }
        return true;
    }

    private String splitArray(char[] chars,int leftIdx,int rightIdx){
        char[] result = new char[rightIdx-leftIdx+1];
        int currentIdx = 0;
        while (leftIdx <= rightIdx){
            result[currentIdx] = chars[leftIdx];
            leftIdx++;
            currentIdx++;
        }
        return new String(result);
    }
}
